#!/usr/bin/python
# -*- coding: utf-8 -*-

from gdata.spreadsheet.service import *
from assis_const               import * 

class Google :
	
	def __init__(self, g_user = None, g_pass = None, g_spreadsheet = None):
		
		self.gd_client          = SpreadsheetsService()
		self.gd_client.email    = g_user
		self.gd_client.password = g_pass
		self.spreadhseet        = g_spreadsheet
		self.gd_client.source   = NAME
		self.ccc_key            = ""
		self.wksht_id			= ""
	
	def set_wrksht_id(self, choice_index):
		
		feed 		  = self.gd_client.GetWorksheetsFeed(self.ccc_key)
		id_parts	  = feed.entry[choice_index].id.text.split('/')
		self.wksht_id = id_parts[len(id_parts) - 1]

	def set_spreadsheet(self, spreadsheet, choice):
		
		feed        	 = self.gd_client.GetSpreadsheetsFeed()
		id_parts    	 = feed.entry[choice].id.text.split('/')
		self.ccc_key	 = id_parts[len(id_parts) - 1]
		self.spreadhseet = spreadsheet

	def render_coordinates(self, text):
		
		abc = map(chr, range(65, 91))
		return abc.index(text[0]), int(text[1:])
		
	def worksheet(self):

		feed = self.gd_client.GetCellsFeed(self.ccc_key, self.wksht_id)
		return feed.entry
		
	def connect(self, name, passwd):

		self.gd_client.email    = name
		self.gd_client.password = passwd
		
		try:
			self.gd_client.ProgrammaticLogin()
		except Error, e:
			print ('ERROR: Google Cloud Connect! : ' + str(e))
			return False
			
		return True
		
	def get_spreadsheets(self):
		
		spreadsheets = []
		feed = self.gd_client.GetSpreadsheetsFeed()
		for entry in feed.entry:
			spreadsheets.append(entry.title.text)
			
		return spreadsheets
			
	def get_worksheets(self):
		
		feed         = self.gd_client.GetSpreadsheetsFeed()
		id_parts     = feed.entry[0].id.text.split('/')
		self.ccc_key = id_parts[len(id_parts) - 1]

		feed = self.gd_client.GetWorksheetsFeed(self.ccc_key)
		worksheets = []
		for i, entry in enumerate(feed.entry):
			worksheets.append(entry.title.text.decode("utf-8", "ignore"))
		
		return worksheets
